package template.service;

import java.io.Serializable;
import java.util.List;

import org.hibernate.criterion.Criterion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;

import template.dao.HibernateDao;
import template.web.Page;
import template.web.PropertyFilter;


/**
 * 领域对象业务管理类基类.
 * 
 * @param <T> 领域对象类型
 * @param <PK> 领域对象的主键类型
 * 
 */
@Transactional
public abstract class EntityManager<T, PK extends Serializable> {

	protected Logger logger = LoggerFactory.getLogger(getClass());

	protected abstract HibernateDao<T, PK> getEntityDao(); 

	// CRUD函数 //
	@Transactional(readOnly = true)
	public T get(final PK id) {
		return getEntityDao().get(id);
	}
	
	@Transactional(readOnly = true)
	public T findByUnique(final String propertyName, final Object value) {
		return getEntityDao().findByUnique(propertyName, value);
	}

	public void save(final T entity) {
		getEntityDao().save(entity);
	}
	
	public void delete(final PK id){
		getEntityDao().delete(id);
	}

	public void delete(final PK... ids) {
		getEntityDao().delete(ids);
	}
	
	@Transactional(readOnly = true)
	public List<T> getAll() {
		return getEntityDao().getAll();
	}
	
	/**
	 * 根据Criterion分页查询
	 * 
	 * @param page 分页参数
	 * @param criterions 数量可变的Criterion
	 * @return
	 */
	@Transactional(readOnly = true)
	public Page<T> setPageDataList(Page<T> page, Criterion... criterions) {
		return getEntityDao().findByCriteria(page, criterions);
	}
	
	/**
	 * 根据PropertyFilter分页查询
	 * 
	 * @param page 分页参数
	 * @param filters PropertyFilter列表
	 * @return
	 */
	@Transactional(readOnly = true)
	public Page<T> setPageDataList(Page<T> page, List<PropertyFilter> filters) {
		return getEntityDao().findByPropertyFilters(page, filters);
	}
	
}
